package com.tezign.intelligence.mini.dam.aifamilyconsultant.util;

import cn.hutool.json.JSON;
import cn.hutool.json.JSONUtil;
import io.github.cdimascio.dotenv.Dotenv;
import lombok.extern.slf4j.Slf4j;
import org.jetbrains.annotations.NotNull;

import javax.crypto.*;
import javax.crypto.spec.IvParameterSpec;
import javax.crypto.spec.SecretKeySpec;
import java.nio.charset.StandardCharsets;
import java.security.InvalidAlgorithmParameterException;
import java.security.InvalidKeyException;
import java.security.NoSuchAlgorithmException;
import java.util.Base64;

import static com.tezign.intelligence.mini.dam.aifamilyconsultant.constant.Constant.*;

@Slf4j
public class AESUtil {

	private static final String ALGORITHM = "AES/CBC/PKCS5Padding";

	/**
	 * 加密
	 */
	public static String encrypt(String data) {
		try {
			AES aes = getAes();
			aes.cipher.init(Cipher.ENCRYPT_MODE, aes.keySpec, aes.ivSpec);
			byte[] encrypted = aes.cipher.doFinal(data.getBytes());
			return Base64.getEncoder().encodeToString(encrypted);
		} catch (Exception e) {
			log.error("encrypt e", e);
			throw new RuntimeException(e);
		}
	}
	/**
	 * 解密
	 */
	public static String decrypt(String encryptedData) {
		try {
			AES aes = getAes();
			aes.cipher.init(Cipher.DECRYPT_MODE, aes.keySpec, aes.ivSpec);
			byte[] decrypted = aes.cipher.doFinal(Base64.getDecoder().decode(encryptedData));
			return new String(decrypted, StandardCharsets.UTF_8);
		} catch (Exception e) {
			log.error("decrypt e", e);
			throw new RuntimeException(e);
		}
	}


	@NotNull
	private static AES getAes() throws NoSuchAlgorithmException, NoSuchPaddingException {
		Dotenv dotenv = Dotenv.load();
		String key = dotenv.get(AES_KEY);
		String iv = dotenv.get(AES_IV);
		Cipher cipher = Cipher.getInstance(ALGORITHM);
		SecretKeySpec keySpec = new SecretKeySpec(key.getBytes(StandardCharsets.UTF_8), "AES");
		IvParameterSpec ivSpec = new IvParameterSpec(iv.getBytes(StandardCharsets.UTF_8));
		return new AES(cipher, keySpec, ivSpec);
	}

	private static class AES {
		public final Cipher cipher;
		public final SecretKeySpec keySpec;
		public final IvParameterSpec ivSpec;

		public AES(Cipher cipher, SecretKeySpec keySpec, IvParameterSpec ivSpec) {
			this.cipher = cipher;
			this.keySpec = keySpec;
			this.ivSpec = ivSpec;
		}
	}


	public static void main(String[] args) throws Exception {
//		String key = "1234567890123456"; // 16字节的密钥
//		String iv = "1234567890123456";  // 16字节的初始化向量
		String data = "Hello, AES CBC!";

		String encrypted = encrypt(data);
		System.out.println("加密后：" + encrypted);

		String decrypted = decrypt(encrypted);
		System.out.println("解密后：" + decrypted);
	}
}
